import {
  Get,
  Post,
  Put,
  Delete,
  Body,
  Controller,
  Param,
} from '@nestjs/common';
import { ArticleService } from './article.service';
import { ArticleEntity } from './article.entity';
import { CreateArticleDto } from './create-article.dto';
import slug from 'slug';

/**
 * 当我们使用了article 路由前缀，因此当我们发起 `/article`的GET请求时，会调用 findAll方法
 * 发起`/article`的POST请求时，会调用create 方法
 */
@Controller('article')
export class ArticleController {
  constructor(private readonly articleService: ArticleService) {}
  @Get()
  findAll(): Promise<ArticleEntity[]> {
    return this.articleService.findAll();
  }

  @Post()
  async create(@Body() articleData: CreateArticleDto) {
    const article = new ArticleEntity();
    article.title = articleData.title;
    article.description = articleData.description;
    article.slug = this.slugify(articleData.title);
    return this.articleService.create(article);
  }

  // 接收路由参数
  @Put(':slug')
  async update(@Param() params, @Body() articleData: CreateArticleDto) {
    return this.articleService.update(params.slug, articleData);
  }

  @Delete(':slug')
  async delete(@Param() params) {
    return this.articleService.delete(params.slug);
  }

  /**
   * 标题别名，标题名 + ‘-’ + 随机字符串
   * @param title 文章标题
   */
  slugify(title: string): string {
    return (
      slug(title, { lower: true }) +
      '-' +
      ((Math.random() * Math.pow(36, 6)) | 0).toString(36)
    );
  }
}
